package com.example.TCP_measure;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Calendar;

public class show_network extends AppCompatActivity {
    MyTask myTask;
    TextView textViewThroughput,textViewDelay;//两个文本框
    LinearLayout linearLayout;
    Socket socket;
    String IP;
    int port;
    BufferedWriter bw=null;
    BufferedReader br=null;
    Calendar calendar;
    Handler handler;
    double[] delay;
    double[] throughput;
    int times;//限制一下单次测量时长，免得它无限跑
    Context context;
    private static final String TAG = "show_network";
    private class MyTask extends AsyncTask<Void,String,Boolean>{
        protected void onPreExecute(){
            handler=new Handler(){
                @Override
                public void handleMessage(Message msg){
                    super.handleMessage(msg);
                    String temp=msg.obj+"";
                    temp=temp.substring(0,5);
                    throughput[times]=Double.parseDouble(temp);
                    textViewThroughput.setText(temp+"Mbs");
                }
            };
        }
        @Override
        protected Boolean doInBackground(Void... voids) {
            try {
                //建立socket  以及io
                socket=new Socket(IP,port);
                socket.setSoTimeout(3000);//超过3秒认为超时

                InputStream inputStream=socket.getInputStream();
                OutputStream outputStream=socket.getOutputStream();
                bw = new BufferedWriter(new OutputStreamWriter(outputStream));
                br = new BufferedReader(new InputStreamReader(inputStream));
                //获得当前时间
                calendar=Calendar.getInstance();//获取发送包时的毫秒数
                bw.write("begin\n");
                bw.flush();
                Log.d("Throughput",bw+"");
                publishProgress("success");
            } catch (UnknownHostException e) {
                publishProgress("low");
            } catch (IOException e) {
                publishProgress("low");
            }
            try {
                String data = null;
                while((data=br.readLine()).equals("receive")&&times<10){
                    Log.d("abcdefghijk",times+"");
                    long time=calendar.getTimeInMillis();
                    calendar=Calendar.getInstance();//获取收到服务器反馈时的时间
                    long temp=calendar.getTimeInMillis();
                    delay[times]=temp-time;//用于画柱状图


                    //在这里建立子线程，然后把子线程中存在的吞吐量用一个static变量存起来  返回给主线程累加，，从而得到最终的吞吐量
                    int max=3;
                    Throughput[] throughput=new Throughput[max];
                    for(int i=0;i<max;++i){
                        throughput[i]=new Throughput(IP,port,null);
                        throughput[i].start();
                    }
                    for(int i=0;i<max;++i){
                        //主线程其他工作完毕,等待子线程的结束, 调用join系列的方法即可(可以设置超时时间)
                        try {
                            throughput[i].join();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try{
                        throughput[0]=new Throughput(IP,port,handler);
                        throughput[0].start();
                        throughput[0].join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    calendar=Calendar.getInstance();//获取发送包时的毫秒数
                    bw.write("begin\n");
                    bw.flush();
                    ++times;
                    //将延迟传递给主函数
                    publishProgress((temp-time)+"");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            return true;
        }
        @Override
        protected void onProgressUpdate(String... progress){
            if(progress[0].equals("success")) {
                Toast.makeText(show_network.this,"连接成功",Toast.LENGTH_SHORT).show();
            }
            else if(progress[0].equals("low")) {
                Toast.makeText(show_network.this,"连接失败",Toast.LENGTH_SHORT).show();
            }else{
                textViewDelay.setText(progress[0]+"ms");
            }
            super.onProgressUpdate(progress);
            Log.d("abcdefg",times+"");
            if(times>=10){
                Log.d("abcdefg","finished");
                //画柱状图 延迟
                int[] Y={10,20,30,40,50,60,70,80};

                Histogram histogram=new Histogram(context,"过去一段时间的网络延迟","延迟/ms",Y,delay,5);

                linearLayout=(LinearLayout)findViewById(R.id.view1);
                linearLayout.addView(histogram);

                //画柱状图 吞吐量
                int[] Y1={10,20,30,40,50,60,70,80};
                for(int i=0;i<10;++i){
                    throughput[i]=throughput[i]*10;
                }
                Histogram histogram1=new Histogram(context,"过去一段时间的网络吞吐量","吞吐量/100Kbs",Y1,throughput,5);

                linearLayout=(LinearLayout)findViewById(R.id.view2);
                linearLayout.addView(histogram1);
            }
        }
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.network_layout);
        context=this;
        times=0;
        delay=new double[10];
        Arrays.fill(delay,(double)0.0);
        throughput=new double[10];
        Arrays.fill(throughput,(double)0.0);
        textViewThroughput=(TextView)findViewById(R.id.textView2);
        textViewDelay=(TextView)findViewById(R.id.textView3);
        Intent intent=getIntent();
        IP=intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        port=Integer.parseInt(intent.getStringExtra(MainActivity.EXTRA_MESSAGE2));
        myTask=new MyTask();
        myTask.execute();
    }
}